<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span>系统：</span>
      <el-select v-model="listQuery.platform" clearable placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <span style="margin-left:10px">版本：</span>
      <el-select v-model="listQuery.apiVersion" clearable placeholder="请选择">
        <el-option
          v-for="item in versionListOptions"
          :key="item.val"
          :label="item.name"
          :value="item.val">
        </el-option>
      </el-select>
      <span style="margin-left:10px">区域：</span>
      <el-select v-model="listQuery.feature" clearable placeholder="请选择">
        <el-option
          v-for="item in featureOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <span style="margin-left:10px">名称：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="搜索名称" v-model="listQuery.searchName">
      </el-input>
      <span style="margin-left:10px">投放区域：</span>
      <el-select v-model="listQuery.areaName" clearable placeholder="请选择">
        <el-option
          v-for="item in areaOptions"
          :key="item.value"
          :label="item.label"
          :value="item.label">
        </el-option>
      </el-select>
    </div>

    <div class="filter-container" style="margin-bottom:20px">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleAllDelete" :type="pageBoolean.delColor" icon="el-icon-delete">{{ pageBoolean.delText }}</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column  v-if='showAllDel' type="selection" width="55">
      </el-table-column>
      
      <el-table-column min-width="60" align="center" label="系统">
        <template slot-scope="scope">
          <span>{{scope.row.platform}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="95" align="center" label="版本号">
        <template slot-scope="scope">
          <span>{{scope.row.apiVersion}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="友盟打点" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.eventId}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="显示区域" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.feature | statusFilter}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="显示名称" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="180" align="center" label="活动icon" show-overflow-tooltip>
        <template slot-scope="scope">
          <div class="icon-ctx">
            <img :src="scope.row.image" style="height:95px"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column min-width="200" align="center" label="投放区域" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.areaName}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="跳转" min-width="260" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.link}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="活动状态" min-width="95">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.statusLabel}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="160" align="center" label="发布日期" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.startTime | dateformat('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="220">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleOprate(scope.row)" v-if="scope.row.toggle && scope.row.statusLabel != '已过期'">下架</el-button>
          <el-button size="small" type="primary" @click="handleOprate(scope.row)" v-if="!scope.row.toggle && scope.row.statusLabel != '已过期'">上架</el-button>
          <el-button size="small" @click="handleModifyStatus(scope.row)">编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
        :page-sizes="[5,10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog top="4%" width="70%" title="编辑页" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="100px" style='width: 70%; margin-left:50px;'>
        <div class="createPost-main-container">
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="位置：" class="postInfo-container-item">
              <el-select v-model="temp.feature" placeholder="请选择位置">
                <el-option
                  v-for="item in featureOptions2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="110px" label="系统：" class="postInfo-container-item">
              <el-select v-model="temp.platform" placeholder="请选择系统">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-tooltip  class="item" effect="dark" content="请输入名称（限10个字符）" placement="top">
              <el-form-item label-width="110px" label="名称：" class="postInfo-container-item" prop="name">
                <el-input style="max-width:280px" placeholder="请输入名称（限10个字符）" maxlength="10" v-model="temp.name">
                </el-input>
              </el-form-item>
            </el-tooltip>
          </el-col>
          <el-col :span="12">
              <el-form-item label-width="110px" label="顺序："  class="postInfo-container-item" prop="number">
                <el-input-number  v-model="temp.sort" :step="1"></el-input-number>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <template v-if="temp.feature == 'TOOL_CONFIG'">
              <el-col :span="12">
                <el-tooltip  class="item" effect="dark" content="请输入跳转链接" placement="top">
                  <el-form-item label-width="110px" label="跳转链接：" class="postInfo-container-item" prop="skipRemarks">
                    <el-input  placeholder="请输入跳转链接" v-model="temp.skipRemarks">
                    </el-input>
                  </el-form-item>
                </el-tooltip>
              </el-col>
          </template>
          <template v-else>
              <el-col :span="12">
                <el-form-item label-width="110px" label="跳转类型：" class="postInfo-container-item" prop="skip">
                  <el-select v-model="temp.skip" placeholder="请选择跳转类型">
                    <el-option
                      v-for="item in brandListOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                  <el-tooltip  class="item" effect="dark" :content="holderVal.placeholder" placement="top">
                    <el-form-item label-width="110px" :label="holderVal.name" class="postInfo-container-item" prop="skipRemarks">
                      <el-input  :placeholder="holderVal.placeholder" v-model="temp.skipRemarks">
                      </el-input>
                    </el-form-item>
                  </el-tooltip>
                </el-col>
          </template>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="是否全版本：" class="postInfo-container-item">
              <el-select v-model="isChoAll" placeholder="请选择全版本">
                <el-option
                  v-for="item in choAllOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="版本："  class="postInfo-container-item" prop="number" v-show="!isChoAll">
              <el-select  style="min-width:480px" v-model="version" multiple placeholder="请选择">
                <el-option
                  v-for="item in versionListOptions2"
                  :key="item.val"
                  :label="item.name"
                  :value="item.val">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
              <el-form-item label-width="110px" label="活动时间：" class="postInfo-container-item" prop="time">  
                <el-date-picker
                  v-model="time"
                  type="datetimerange"
                  :picker-options="pickerOptions2"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right">
                </el-date-picker>
              </el-form-item>
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label-width="110px" label="图片：" class="postInfo-container-item">
              <el-upload
              :headers="headers"
              action="/tools/oss/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              list-type="picture"
               :file-list="temp.file"
              :limit="1">
              <el-button size="small" type="primary" icon="el-icon-upload2">点击此处上传图片</el-button>
              <div slot="tip" class="el-upload__tip">注：建议尺寸：{{ temp.feature == 'TOOL_CONFIG' ? '96X96px' : temp.feature == 'EXPERT_BANNERS' ? '972X382px' : temp.feature == 'RESEARCH_BANNERS' ? '972X382px' : temp.feature == 'LIVE_BANNERS' ? '976X468px' : '像素 1029 * 444 长宽比 2.31' }}</div>
            </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label-width="110px" label="投放区域：" class="postInfo-container-item">
              <el-select v-model="temp.areaName" placeholder="请选择投放区域">
                <el-option
                  v-for="item in areaOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
      </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, delId, delIds, update, getVersions, getId, toggleId, getAreaList } from '@/api/activity'
import { getToken } from '@/utils/auth' // 验权
import { validateURL } from '@/utils/validate'

export default {
  name: 'list',
  data() {
    return {
      areaOptions: [], // 省份列表
      version:[],
      time:[],
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      brandListOptions: [{
        id:'lesson_detail',
        name:'课程'
      }, {
        id:'infomation_detail',
        name:'资讯'
      }, {
        id:'url',
        name:'网页'
      }],
      holderVal:{
        placeholder:'请输入商品ID',
        name:'商品ID：'
      },
      holderMap:{
        'lesson_detail':{
          placeholder:'请输入商品ID',
          name:'商品ID：'
        },
        'infomation_detail':{
          placeholder:'请输入资讯ID',
          name:'资讯ID：'
        },
        'url':{
          placeholder:'请输入跳转链接',
          name:'跳转链接：'
        }
      },
      temp: {
        feature:'HOMEPAGE_BANNERS',
        id:'',
        apiVersion:[],
        sort:1,
        image:'',
        name:'',
        platform:'ALL',
        skipRemarks:'',
        skip:'lesson_detail'
      },
      options:[{
        value: 'ALL',
        label: '所有'
      }, {
        value: 'IOS_IPHONE',
        label: 'iOS'
      }, {
        value: 'AM',
        label: '安卓'
      }],
      featureOptions: [{
        value: '',
        label: '所有'
      }, {
        value: 'HOMEPAGE_BANNERS',
        label: '首页Banner'
      }, {
        value: 'LIVE_BANNERS',
        label: '课程Banner'
      }, {
        value: 'EXPERT_BANNERS',
        label: '专家Banner'
      }, {
        value: 'RESEARCH_BANNERS',
        label: '研学Banner'
      }, {
        value: 'TOOL_CONFIG',
        label: '工具页'
      }],
      featureOptions2: [{
        value: 'HOMEPAGE_BANNERS',
        label: '首页Banner'
      }, {
        value: 'LIVE_BANNERS',
        label: '课程Banner'
      }, {
        value: 'EXPERT_BANNERS',
        label: '专家Banner'
      }, {
        value: 'RESEARCH_BANNERS',
        label: '研学Banner'
      }, {
        value: 'TOOL_CONFIG',
        label: '工具页'
      }],
      headers:{},
      inputVisible:false,
      inputValue:'',
      versionListOptions: [],
      versionListOptions2: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      dateformat:'',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        'apiVersion': '',
        'feature': '',
        'features': [],
        'keyword': '',
        'orderBy': '',
        'pageNo': 1,
        'pageSize': 5,
        'platform': 'ALL',
        'searchName': '',
        'sortField': '',
        'areaName': ''
      },
      temp: {
        labels:[]
      },
      dialogFormVisible: false,
      rules: {
        skip: [{ required: true, message: '跳转类型必选', trigger: 'change' }],
        name: [{ required: true, message: '名称必填', trigger: 'blur' }],
        skipRemarks: [{ required: true, message: '内容必填', trigger: 'blur' }]
      },
      tableKey: 0,
      showAllDel:false,
      multipleSelection:[],
      pageBoolean:{
        delColor:'primary',
        delText:'批量删除'
      },
      isChoAll: false,
      choAllOption: [{
        value: true,
        label: '是'
      }, {
        value: false,
        label: '否'
      }]
    }
  },
  mounted() {
    this.getVersions()
    this.fetchAreaData()
    this.getList()
    this.headers = { accessToken:getToken() }
  },
  watch:{
    'temp.feature'(val){
      if(val == 'TOOL_CONFIG'){
        this.temp['skip'] = 'url'
      }else{
        //this.temp['skip'] = 'lesson_detail'
      }
    },
    'temp.skip'(val){
      this.holderVal = this.holderMap[val]
    },
    isChoAll(boolean) {
      if (boolean) {
        this.version = []
      }
    },
    showAllDel(val){
      if(val){
        this.pageBoolean.delText = '选择删除'
        this.pageBoolean.delColor = 'danger'
      }else{
        this.pageBoolean.delText = '批量删除'
        this.pageBoolean.delColor = 'primary'
      }
    },
    multipleSelection(val){
      if(val.length == 0){
        this.pageBoolean.delText = '选择删除'
        this.pageBoolean.delColor = 'danger'
      }else{
        this.pageBoolean.delText = '确定删除'
        this.pageBoolean.delColor = 'success'
      }
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        tool_config:'工具页',
        live_banners:'课程Banner',
        homepage_banners:'首页Banner',
        TOOL_CONFIG:'工具页',
        LIVE_BANNERS:'课程Banner',
        HOMEPAGE_BANNERS:'首页Banner',
        EXPERT_BANNERS: '专家Banner',
        RESEARCH_BANNERS: '研学Banner'
      }
      return statusMap[status]
    }
  },
  methods: {
    handleOprate(row){
      toggleId(row.id).then(res => {
        const { code } = res
        if(code == 0){
          this.$notify({
            message: `${row.toggle ? '下架' : '上架'}成功`,
            type: 'success',
            duration: 2000
          })
          row.statusLabel = row.toggle ? '已下架' : '投放中'
          row.toggle = !row.toggle
        }
      })
    },
    handleUploadSuccess(rst){
      const { code, data:{ picUrlList } } = rst
      const { temp } = this
      if(code == 0){
        temp['image'] = picUrlList[0]
      }
    },
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      this.temp['image'] = ''
      this.temp['file'] = []
    },
    handleClose(tag) {
      this.temp.labels.splice(this.temp.labels.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.labels.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    getVersions() {
      getVersions().then(response => {
        const { code, data } = response
        if(code == 0){
          const versionList = []
          data.map(e => versionList.push({ name:e, val:e }))
          this.versionListOptions2 = versionList
          this.versionListOptions = [{ name:'所有', val:'' }, { name:'ALL', val:'all' }, ...versionList]
        }
      })
    },
    handleSelectionChange(val){
      this.multipleSelection = val
    },
    handleAllDelete(){
      const { showAllDel, multipleSelection } = this
      if(multipleSelection.length != 0){
        const ids = []
        multipleSelection.map(e => ids.push(e.id))
        delIds(ids).then(response => {
          const { code } = response
          if(code == 0){
            this.$notify({
              title: '成功',
              message: '批量删除资讯成功',
              type: 'success',
              duration: 2000
            })
            this.handleRefresh()
          }else{
            this.$notify({
              title: '失败',
              message: '批量删除资讯失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }
      this.showAllDel = !showAllDel
    },
    getList() {
      this.listLoading = true
      const params = this.listQuery
      if(params['feature'].length != 0){
        params['features'] = [params['feature']]
      }else{
        params['features'] = []
      }
      getList(params).then(response => {
        const { code, data:{ total, data } } = response
        if(code == 0){
          this.total = total
          this.list = data
          console.log('list', this.list)
          this.listLoading = false
        }
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleModifyStatus(row) {
      getId(row.id).then(response => {
        const { code, data } = response
        const { apiVersion, platform } = data
        this.time = [new Date(data.startTime), new Date(data.endTime)]
        data['file'] = [{ name:data.image, url:data.image }]
        data['areaName'] = row.areaName
        if(apiVersion.length != 0){
          let arr = []
          if(apiVersion == 'all'){
            // const {versionListOptions2} =  this;
            // versionListOptions2.map(e=>arr.push(e.val));
            this.isChoAll = true
            this.version = []
          }else{
            arr = apiVersion.split(',')
            this.isChoAll = false
          }
          this.version = arr
          data['platform'] = platform
        }
        this.temp = data
        this.dialogFormVisible = true
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const { temp } = this
          const { temp:{ feature, skip, skipRemarks }, time, version } = this
          console.log('time', time)
          if(!time){
            this.$notify({
              message: '活动时间必填',
              type: 'error',
              duration: 1000
            })
            return
          }
          if(skip == 'lesson_detail' || skip == 'infomation_detail'){
            if(!/^\d+$/.test(skipRemarks.trim())){
              this.$notify({
                message: '请输入数字',
                type: 'error',
                duration: 1000
              })
              return
            }
          }else if(skip == 'url'){
            if(!validateURL(skipRemarks.trim())){
              this.$notify({
                message: '请输入正确的url',
                type: 'error',
                duration: 1000
              })
              this.loading = false
              return
            }
          }
          if(this.isChoAll) {
            temp['apiVersion'] = 'all'
          } else {
            temp['apiVersion'] = version.join(',')
          }
          temp['startTime'] = time[0].getTime()
          temp['endTime'] = time[1].getTime()
          update(temp).then(response => {
            const { code } = response
            if(code == 0){
              this.list.map((e, i) => {
                if(e.id === temp.id){
                  const newTemp = Object.assign({}, e, temp)
                  if(isNaN(temp['skipRemarks'])){
                    newTemp['items'] = [{ link:temp['skipRemarks'], image:temp['image'] }]
                  }else{
                    newTemp['items'] = [{ link:`shengxue://lessonDetail?id=${temp['skipRemarks']}`, image:temp['image'] }]
                  }
                  this.list.splice(i, 1, newTemp)
                }
              })
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(idx, row) {
      this.$confirm('是否要删除该活动？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { id } = row
        delId(id).then(response => {
          const { code } = response
          if(code == 0){
            this.$notify({
              title: '成功',
              message: '删除资讯成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(idx)
            this.list.splice(idx, 1)
            this.total--
          }else{
            this.$notify({
              title: '失败',
              message: '删除资讯失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {})
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getList()
    },
    fetchAreaData() {
      getAreaList().then(response => {
        this.areaOptions = response.data
        this.areaOptions.unshift({
          value: 100001,
          label: '全国',
          children: []
        })
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.icon-ctx{
  width:160px;
  height:100px;
  overflow:hidden;
  margin:0 auto;
}
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container{
  padding:20px;
}
.pagination-container{
  margin-top:30px;
}
</style>